package test;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.print.DocFlavor.INPUT_STREAM;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

public class MySQLRemoveJP extends JFrame {
	JTextArea textArea = new JTextArea();
	JButton button = new JButton("run");
	private String actionKey = "action1";
	JScrollPane scrollPane;
	JList jlist;
	ArrayList<MyProperties> keyProperties;
	
	final UndoManager undo = new UndoManager();
	Document doc = textArea.getDocument();

	public MySQLRemoveJP() throws HeadlessException {
		super("Nhan JP Name SQL remover v1.1");
		keyProperties = new ArrayList<MyProperties>();
		String normalTableNameReplacesMent = "sqlBuf.append(businessDBUser).append(\".\");\n";
		keyProperties.add(new MyProperties("SYMPHONIZER_NORMAL_TABLE.",
				normalTableNameReplacesMent));
		String sysTableNameReplacesMent = "sqlBuf.append(basicUser).append(\".\");\n";
		keyProperties.add(new MyProperties("SYMPHONIZER_SYSTEM_TABLE.",
				sysTableNameReplacesMent));

		textArea.setFont(new Font("Courier New", 0, 20));

		
		// Listen for undo and redo events
		doc.addUndoableEditListener(new UndoableEditListener() {
		    public void undoableEditHappened(UndoableEditEvent evt) {
		        undo.addEdit(evt.getEdit());
		    }
		});

		// Create an undo action and add it to the text component
		textArea.getActionMap().put("Undo",
		    new AbstractAction("Undo") {
		        public void actionPerformed(ActionEvent evt) {
		            try {
		                if (undo.canUndo()) {
		                    undo.undo();
		                }
		            } catch (CannotUndoException e) {
		            }
		        }
		   });

		// Bind the undo action to ctl-Z
		textArea.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");

		// Create a redo action and add it to the text component
		textArea.getActionMap().put("Redo",
		    new AbstractAction("Redo") {
		        public void actionPerformed(ActionEvent evt) {
		            try {
		                if (undo.canRedo()) {
		                    undo.redo();
		                }
		            } catch (CannotRedoException e) {
		            }
		        }
		    });

		// Bind the redo action to ctl-Y
		textArea.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
		
		
		
		
		final JPopupMenu popupMenu = new JPopupMenu();
		JMenuItem menuItemRun = new JMenuItem("Run appender...");
		popupMenu.add(menuItemRun);
		
//		textArea.add(popupMenu);
		
//		textArea.add(popupMenu);
		
		textArea.addMouseListener(new MouseListener() {
			
			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mousePressed(MouseEvent e) {
				if(e.getButton() == e.BUTTON3)
				popupMenu.show(e.getComponent(), e.getX(), e.getY());
				
			}
			
			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		
		menuItemRun.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				runAction();

			}
		});

		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				runAction();
			}
		});
		Action actionListener = new AbstractAction() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int x = (int) textArea.getCaret().getMagicCaretPosition()
						.getX();
				int y = (int) textArea.getCaret().getMagicCaretPosition()
						.getY();
				scrollPane.setBounds(x, y + 20, 250, 100);
				scrollPane.setVisible(true);
				jlist.setSelectedIndex(0);
				jlist.requestFocus();

			}
		};

		String[] keys = new String[keyProperties.size()];
		for (int i = 0; i < keys.length; i++) {
			keys[i] = keyProperties.get(i).getKey();
		}
		jlist = new JList(keys);
		textArea.setLayout(null);
		scrollPane = new JScrollPane(jlist);
		textArea.add(scrollPane);
		scrollPane.setBounds(0, 0, 100, 50);
		scrollPane.setVisible(false);
		jlist.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
				System.out.println((int) e.getKeyChar());
				if ((int) e.getKeyChar() == 10) {
					String dataSelected = (String) jlist.getSelectedValue();
					scrollPane.setVisible(false);
					textArea.requestFocus();
					textArea.getCaretPosition();
					try {
						int pos = textArea.getCaretPosition();
						String before = textArea.getText(0, pos);
						String after = textArea.getText(pos, textArea.getText()
								.length() - (pos));
						String text = before + dataSelected + after;
						textArea.setText(text);
						textArea.setCaretPosition(pos + dataSelected.length());
					} catch (BadLocationException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				}
			}

			@Override
			public void keyReleased(KeyEvent e) {

			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});

		InputMap inputMap = textArea.getInputMap();
		ActionMap actionMap = textArea.getActionMap();
		KeyStroke ctrlSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,
				InputEvent.CTRL_DOWN_MASK);
		inputMap.put(ctrlSpace, this.actionKey);
		actionMap.put(actionKey, actionListener);

		textArea.requestFocus();
		
		this.getContentPane().add(new JScrollPane(textArea));
		this.getContentPane().add(button, BorderLayout.NORTH);
		this.setSize(800, 600);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);

	}

	
	public void runAction(){
		StringBuffer s = new StringBuffer();

		String text = textArea.getText();
		for (int i = 0; i < text.length(); i++) {
			char ci = text.charAt(i);
			int ciCode = (int) ci;
			if ( (48 <= ciCode && ciCode <= 57) 
					|| (65 <= ciCode && ciCode <= 90) 
					|| (97 <= ciCode && ciCode <= 122)
					|| '+' == ci 
					|| '-' == ci 
					|| '*' == ci 
					|| '/' == ci 
					|| '%' == ci 
					|| '\'' == ci 
					|| '\"' == ci 
					|| ' ' == ci 
					|| '\n' == ci 
					|| ':' == ci 
					|| '?' == ci 
					|| '=' == ci 
					|| ',' == ci 
					|| '.' == ci 
					|| '(' == ci 
					|| ')' == ci 
					|| '_' == ci 
					) {
				s.append(ci);
			}
		}
		String textAfterRemoveJP = s.toString();
//		s = new StringBuffer();
//		StringBuffer temp = new StringBuffer();
//		boolean flgMoNgoac = false;
//		boolean coDuLieu = false;
//		
//		for (int i = 0; i < textAfterRemoveJP.length(); i++) {
//			char ci = textAfterRemoveJP.charAt(i);
//			if (ci == '(') {
//				flgMoNgoac = true;
//				if (coDuLieu){
//					String tempData = temp.toString();
//					temp = new StringBuffer();
//					s.append(tempData);
//				}
//				temp.append( "(");
//			} else {
//				if (flgMoNgoac) {
//					if (ci != ')') {
//						coDuLieu = true;
//						if (ci != ' ') {
//							temp.append(ci);
//						}
//					} else {// ")"
//						if (coDuLieu) {
//							temp.append(")");
//							String tempData = temp.toString();
//							s.append(tempData);
//						}
//						
//						coDuLieu = false;
//						temp = new StringBuffer();
//						flgMoNgoac = false;
//					}
//				} else {// không co mở ngoặc, dữ liệu thường
//						s.append(ci);
//				}
//			}
//		}
		textAfterRemoveJP = textAfterRemoveJP.replaceAll(Pattern.quote("()"), "");
		//textArea.setText(s.toString());
		String oldText = textArea.getText();
		s = new StringBuffer();
		s.append(oldText);
		s.append("\n-------------Kết quả---------------\n");
		s.append(textAfterRemoveJP);
		textArea.setText(s.toString());
		textArea.requestFocus();
	}
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new MySQLRemoveJP();

	}

}
